var thesum=0;    //跟进内容返回数量
var resdata=[];  //跟进内容返回数据
var theadd = 0;
var username = sessionStorage.getItem("name"); 
var userid = sessionStorage.getItem("userId"); 
var now = getNowFormatDate();
$('#name').text(sessionStorage.getItem("name"));
var _config ;
var addtof =true;  //当天能否跟进
var photoUrl = [];//拍照列表
var sendData = {};  //待办事项
sendData.planuserid = sessionStorage.getItem("userId");
var url  = location.search;
var theRequest = new Object();  
if ( url.indexOf( "?" ) != -1 ){  
var str = url.substr( 1 ); //substr()方法返回从参数值开始到结束的字符串；  
var strs = str.split( "&" ); 
var plantype=1; 
var pno,mno,ino;
for ( var i = 0; i < strs.length; i++ ) {  
theRequest[ strs[ i ].split( "=" )[ 0 ] ] = ( strs[ i ].split( "=" )[ 1 ] );  
}  
} 
sno=theRequest.sno;
processId=theRequest.processId;
processdId=theRequest.processdId;
sendData.sno =sno; 
sendData.processId =processId; 
sendData.processdId =processdId; 
$.ajax({              //待办事项
	url: "../../shop_open_info/getdetailBody"
	,type:'post'
	,async: false
	,contentType: "application/json; charset=utf-8"
	,data:JSON.stringify(sendData) 
	,dataType:'json'
	,success: function(res){
		console.log(res)
		resdata = res.data;
		thesum=resdata.length;
		if(thesum<=0){
			addform();
		}else{
			if(res.data[resdata.length-1].lrsj.substring(0,10)==getNowFormatDate()){addtof=false;}
		}
		 

	},error:function(XMLHttpRequest, textStatus, errorThrown) {
		 alert(JSON.stringify(XMLHttpRequest));
		 alert(JSON.stringify(errorThrown));
		 alert(textStatus);
	}
});
$(document).ready(function(){
	daiban();
	$('#addButton').on('click',addform);
	$('#searchButton').on('click',saveInfo);
	$('#searchButton1').on('click',finishSVInfo);
});	
//获取当前日期
function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
}
function daiban(){  //待办事项
			for(var i=0;i<resdata.length;i++){
				if(resdata[i].jindu==undefined){
					resdata[i].jindu="";
				}if(resdata[i].instructions==undefined){
					resdata[i].instructions="";
				}	
				var photohtml =[];
				if(resdata[i].pic != undefined){
					photohtml = resdata[i].pic.split(",")
				}
				var photodiv = '';
				for(var ss=0;ss<photohtml.length;ss++){
					photodiv = '<div class="wig_img">'
					+'<div class="img_box">'
					+'<img alt="100x100" src="'+photohtml[ss]+'" onclick="showAllPic(\''+photohtml[ss]+'\')"/>'
					+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
					+'</div>'
					+'</div>'
				}
	$('#weiDiv').append('<div class="widget-header widget-header-flat widget-header-small">'   //待办事项标题
					+'<h5 style="font-weight:bold;color:#eb6100;">跟进内容'+(i+1)+'</h5>'
					+'</div>');
	$('#weiDiv').append('<div class="col_box">'                                               //待办事项内容
						+'<div>'		
						+'<div class="widget-box add_mar_tb7p">'			
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'<h5><i class="iconfont">&#xe609;</i>&nbsp;跟进时间<span class="red"></span></h5>'					
						+'<input type="text"  id="lrsj'+i+'"  autocomplete="off"   class="pull-right  layui-input add_bor_none" style="width: 70%;margin-right: 2%;border:none" readonly="readonly" value="'+resdata[i].lrsj+'"/>'					    
						+'</div>'				
						+'</div>'			
						+'</div>'								
						+'<div>'							
						+'<div class="widget-box add_mar_tb7p">'			
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
						+'<h5 id="wentishuomingTitle"><i class="iconfont">&#xe600;</i>&nbsp;跟进内容</h5><span class="red"></span>'
						+'</div>'
						+'<div class="widget-body zhediebox1">'
						+'<div class="widget-main pd_div" style="padding:0;">'
						+'<div class="clearfix jy_div" style="padding:0;">'
						+'<textarea id="instructions'+i+'"  rows="" cols="" class="pull-left  add_pad_tb10p add_bor_none" '+setreadonly(resdata[i])+' >'+resdata[i].instructions+'</textarea>'
						+'</div>'
						+'</div></div></div></div>'			
						+'<div>'		
						+'<div class="widget-box add_mar_tb7p">'			
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'       			
						+'<h5><i class="iconfont">&#xe600;</i>&nbsp;进度<span class="red"></span></h5>'	
						+'<input type="text" id="jindu'+i+'" class="pull-right add_bor_none" autocomplete="off" style="width: 78%;margin-right: 2%;border:none" '+setreadonly(resdata[i])+' value="'+resdata[i].jindu+'" />'
						+'</div>'	
						+'</div>'
						
						
						+'<div>'		
						+'<div class="widget-box">'		
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'	
						+'<h5><i class="iconfont">&#xe621;</i>&nbsp;相关图片</h5>'	
						+'<div class="widget-toolbar no-border" id="paizhao" style="margin-top: 5px">'	
						+'<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
						+'</div>'
						+'</div>'
						+'<div class="widget-body">'
						+'<div class="widget-main" id="paizhapoUrl">'
						+'<div class="clearfix">'
						+photodiv
						+'</div>'
						+'</div></div></div></div>'
								
						
						+'</div>'	
						+'</div>'
		);
}
	$('#paizhao').on('click',function(){
		openphoto();
	});
}
function addform(){  
   if(addtof){
	$('#paizhao').on('click',function(){
		openphoto();
	});
    addtof=false;
	var i=thesum;			
	$('#weiDiv').append('<div class="widget-header widget-header-flat widget-header-small">'  
					+'<h5 style="font-weight:bold;color:#eb6100;">跟进内容'+(i+1)+'</h5>'
					+'</div>');
	$('#weiDiv').append('<div class="col_box">'                                           
						+'<div>'		
						+'<div class="widget-box add_mar_tb7p">'			
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'<h5><i class="iconfont">&#xe609;</i>&nbsp;跟进时间<span class="red"></span></h5>'					
						+'<input type="text"  id="lrsj"  autocomplete="off"   class="pull-right  layui-input add_bor_none" style="width: 70%;margin-right: 2%;border:none" readonly="readonly" value="'+getNowFormatDatetime()+'"/>'					    
						+'</div>'				
						+'</div>'			
						+'</div>'								
						+'<div>'							
						+'<div class="widget-box add_mar_tb7p">'			
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
						+'<h5 id="wentishuomingTitle"><i class="iconfont">&#xe600;</i>&nbsp;跟进内容</h5><span class="red"></span>'
						+'</div>'
						+'<div class="widget-body zhediebox1">'
						+'<div class="widget-main pd_div" style="padding:0;">'
						+'<div class="clearfix jy_div" style="padding:0;">'
						+'<textarea id="instructions"  rows="" cols="" class="pull-left  add_pad_tb10p add_bor_none" ></textarea>'
						+'</div>'
						+'</div></div></div></div>'			
						+'<div>'		
						+'<div class="widget-box add_mar_tb7p">'			
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'       			
						+'<h5><i class="iconfont">&#xe600;</i>&nbsp;进度<span class="red"></span></h5>'	
						+'<input type="text" id="jindu" class="pull-right  add_bor_none" autocomplete="off" style="width: 78%;margin-right: 2%;border:none"   />'
						+'</div>'	
						+'</div>'
						+'</div>'
						
						+'<div>'		
						+'<div class="widget-box">'		
						+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'	
						+'<h5><i class="iconfont">&#xe621;</i>&nbsp;相关图片</h5>'	
						+'<div class="widget-toolbar no-border" id="paizhao" style="margin-top: 5px">'	
						+'<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
						+'</div>'
						+'</div>'
						+'<div class="widget-body">'
						+'<div class="widget-main" id="paizhapoUrl">'
						+'<div class="clearfix"></div>'
						+'</div></div></div></div>'
						
							
						+'</div>'
	);

	theadd=thesum+1;
  }else{alert("每日只能新增一条跟进内容");}
}
function setreadonly(resdata){
	if(resdata.lrsj.substring(0,10)==getNowFormatDate()){return '';photoUrl = [resdata.pic] }else{return 'readonly="readonly"';}
}
function saveInfo(){
	showloading();
	try {
		var sendData = {};
		var insertArray = [];
		var updateArray = [];
		var updateArrayDetail = [];
		var updateJson = {};
		var insertJson = {};
		var detail = {};
        for(var i=0;i<thesum;i++){
	        var instructions =  document.getElementById('instructions'+i).value;
			var lrsj =  document.getElementById('lrsj'+i).value;
			var jindu =  document.getElementById('jindu'+i).value;
			updateJson.instructions=instructions;
			updateJson.lrsj=lrsj;
			updateJson.jindu=jindu;
			updateJson.pic = photoUrl.join(',');
			updateJson.rno=resdata[i].rno;
			updateJson.sno=sno;
			updateJson.processId=processId;
			updateJson.processdId=processdId;
			updateArray.push(updateJson);
			
			detail.sno=sno;
			detail.processId=processId;
			detail.processdId=processdId;
			detail.jindu=jindu;
			detail.pic = photoUrl.join(',');
			detail.flag=0;
			detail.enddate="";
		}
		
		if(theadd!=0){
		    instructions =document.getElementById('instructions').value;
			lrsj =document.getElementById('lrsj').value;
			jindu =document.getElementById('jindu').value;
			insertJson.sno=sno;
			insertJson.processId=processId;
			insertJson.processdId=processdId;
			insertJson.instructions=instructions;
			insertJson.jindu = jindu;
			insertJson.pic = photoUrl.join(',');
			insertJson.lrsj=lrsj;
			insertJson.lrr = userid;
			insertArray.push(insertJson);
			
			detail.sno=sno;
			detail.processId=processId;
			detail.processdId=processdId;
			detail.jindu=jindu;
			detail.pic = photoUrl.join(',');
			detail.flag=0;
			detail.enddate="";
		}
					
	   updateArrayDetail.push(detail);
       sendData.insertArray=insertArray;
   	   sendData.updateArray=updateArray;
       sendData.updateArrayDetail=updateArrayDetail;
	  $.ajax({
				url: "../../shop_open_info/replyedit"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.status==1000){
						layer.msg(res.msg);
					}else{
						layer.msg('保存成功',{time:1000},function(){
							dd.device.base.getPhoneInfo({
							    onSuccess : function(data) {//iPhone
			                    if(data.brand == iPhone){
									sessionStorage.setItem("Creload", true);
								}
							    },
							    onFail : function(err) {}
							});
							history.go(-1);
						});
					}
				}
			    });
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	
}
function finishSVInfo(){
	sessionStorage.setItem("Creload", true);
	showloading();
	try {
		var sendData = {};
		var insertArray = [];
		var updateArray = [];
		var updateArrayDetail = [];
		var updateJson = {};
		var insertJson = {};
		var detail = {};
        for(var i=0;i<thesum;i++){
	       var instructions =  document.getElementById('instructions'+i).value;
			var lrsj =  document.getElementById('lrsj'+i).value;
			var jindu =  document.getElementById('jindu'+i).value;
			updateJson.instructions=instructions;
			updateJson.lrsj=lrsj;
			updateJson.jindu=jindu;
			updateJson.pic = photoUrl.join(',');
			updateJson.rno=resdata[i].rno;
			updateJson.sno=sno;
			updateJson.processId=processId;
			updateJson.processdId=processdId;
			updateArray.push(updateJson);
			
			detail.sno=sno;
			detail.processId=processId;
			detail.processdId=processdId;
			detail.jindu=jindu;
			detail.pic = photoUrl.join(',');
			detail.flag=1;
			detail.enddate=getNowFormatDatetime();
		}
		if(theadd!=0){
		     instructions =document.getElementById('instructions').value;
			lrsj =document.getElementById('lrsj').value;
			jindu =document.getElementById('jindu').value;
			insertJson.sno=sno;
			insertJson.processId=processId;
			insertJson.processdId=processdId;
			insertJson.instructions=instructions;
			insertJson.jindu = jindu;
			insertJson.pic = photoUrl.join(',');
			insertJson.lrsj=lrsj;
			insertJson.lrr = userid;
			insertArray.push(insertJson);
			
			detail.sno=sno;
			detail.processId=processId;
			detail.processdId=processdId;
			detail.jindu=jindu;
			detail.pic = photoUrl.join(',');
			detail.flag=1;
			detail.enddate=getNowFormatDatetime();
		}
	   updateArrayDetail.push(detail);
       sendData.insertArray=insertArray;
   	   sendData.updateArray=updateArray;
       sendData.updateArrayDetail=updateArrayDetail;
	
	 $.ajax({
				url: "../../shop_open_info/replyedit"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.status==1000){
						layer.msg(res.msg);
					}else{
						layer.msg('该项工作已完成',{time:1000},function(){
						dd.device.base.getPhoneInfo({
							    onSuccess : function(data) {//iPhone
			                    if(data.brand == iPhone){
									sessionStorage.setItem("Creload", true);
								}
							    },
							    onFail : function(err) {}
							});
						history.go(-1);
							/*url = "../../mobile_page/work_plan_info/work_content_search";//此处拼接内容
	                        window.location.href = url;*/
						});
					}
				}
			    });
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	
}
//获取当前日期
function getNowFormatDatetime() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
    	var strDate = date.getDate();
		var hour = date.getHours();
		var minutes = date.getMinutes();
		var seconds = date.getSeconds();
    
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }	
		if (hour >= 0 && hour <= 9) {
            hour = "0" + hour;
        }
  		if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
  		if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate + ' '+hour+':'+minutes+':'+seconds;
        return currentdate;
}
//打开钉钉拍照
function openphoto(){
	if(_config == undefined){
		$.ajax({
			type : "post",
			data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26')}),
			contentType: "application/json; charset=utf-8",
			async: false,
			url : "../../dingding/getconfig",
			dataType : "json",
			success : function(suc) {
//				console.log(suc);
				_config = suc.config;
			}
		}); 
		dd.config({
			agentId : _config.agentid,
			corpId : _config.corpId,
			timeStamp : _config.timeStamp,
			nonceStr : _config.nonceStr,
			signature : _config.signature,
			jsApiList : [ 'runtime.info','biz.util.uploadImage' ]
		});
	}
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: getNowFormatDateTime(),
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
			photoUrl.push(result[0]);
			$('#paizhapoUrl .clearfix').remove()
			$('#paizhapoUrl').append('<div class="wig_img">'
					+'<div class="img_box">'
					+'<img alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
					+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
					+'</div>'
					+'</div>');
			$('#paizhapoUrl').append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
}	
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().parent().index();
	    		$(obj).parent().parent().remove();
	    		photoUrl.splice(index,1);
	    	}
	        
	    },
	    onFail : function(err) {}
	});
	 
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: photoUrl,//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}